package operator.transfer;

import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import util.Printer;

class ScanOperator {

    public static void main(String[] args) {
        scan1();
        scan2();
    }


    /**
     * Scan操作符对原始Observable发射的第一项数据应用一个函数，然后将那个函数的结果作为自己的第一项数据发射
     * 它将函数的结果同第二项数据一起填充给这个函数来产生它自己的第二项数据
     *
     */
    static void scan1() {
        Observable.range(1, 20)
                .scan(new BiFunction<Integer, Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer, Integer integer2) throws Exception {
                        return integer + integer2;
                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Printer.print(integer.toString());
                    }
                });
    }

    static void scan2() {
        Observable.just("1", "2", "3")
                .scan(new BiFunction<String, String, String>() {
                    @Override
                    public String apply(String s1, String s2) throws Exception {
                        return s1 + " " +s2;
                    }
                })
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String result) throws Exception {
                        Printer.print(result);
                    }
                });

        Observable.just("4", "5", "6")
                .scan("start", new BiFunction<String, String, String>() {
                    @Override
                    public String apply(String s, String s2) throws Exception {
                        return s + " " + s2;
                    }
                })
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String result) throws Exception {
                        Printer.print(result);
                    }
                });


    }


}
